package com.xiyu.service.repository.material.order;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.order.MaterialPurchaseDetail;
import com.xiyu.service.model.material.order.MaterialPurchaseDetailFetcher;
import com.xiyu.service.model.material.order.MaterialPurchaseDetailTable;
import org.babyfish.jimmer.spring.repository.JRepository;

import java.math.BigDecimal;
import java.util.List;

public interface MaterialPurchaseDetailRepository extends JRepository<MaterialPurchaseDetail, Long> {
    MaterialPurchaseDetailTable materialPurchaseDetailTable = MaterialPurchaseDetailTable.$;

    List<MaterialPurchaseDetail> findByPurchaseId(Long purchaseId);

    default List<MaterialPurchaseDetail> findDetailByPurchaseId(Long purchaseId){
        return sql().createQuery(materialPurchaseDetailTable)
                .where(materialPurchaseDetailTable.purchaseId().eq(purchaseId))
                .select(materialPurchaseDetailTable.fetch(MaterialPurchaseDetailFetcher.$.allTableFields()
                        .material(MaterialInfoFetcher.$.allTableFields()
                                .category(MaterialCategoryFetcher.$.allTableFields()))
                        )
                )
                .execute();
    }

    default List<MaterialPurchaseDetail> findByDetailColumn(Long purchaseId, Long materialId, String batchNo,
                                                            String productionDate, String expireDate){
        return sql().createQuery(materialPurchaseDetailTable)
                .where(materialPurchaseDetailTable.purchaseId().eq(purchaseId))
                .where(materialPurchaseDetailTable.materialId().eq(materialId))
                .where(materialPurchaseDetailTable.batchNo().eq(batchNo))
                .where(materialPurchaseDetailTable.productionDate().eq(productionDate))
                .where(materialPurchaseDetailTable.expireDate().eq(expireDate))
                .select(materialPurchaseDetailTable)
                .execute();
    }

    default void updateInNumberById(Long id, BigDecimal inNumber){
        sql().createUpdate(materialPurchaseDetailTable)
                .set(materialPurchaseDetailTable.inNumber(), materialPurchaseDetailTable.inNumber().plus(inNumber))
                .where(materialPurchaseDetailTable.id().eq(id))
                .execute();
    }

    default long findUnInByPurchaseId(Long purchaseId){
        return sql().createQuery(materialPurchaseDetailTable)
                .where(materialPurchaseDetailTable.purchaseId().eq(purchaseId))
                .where(materialPurchaseDetailTable.number().gt(materialPurchaseDetailTable.inNumber()))
                .select(materialPurchaseDetailTable.id().count())
                .fetchOne();
    }
}